// server.cc

#include <string>
#include <vector>
#include <iostream>
#include <grpcpp/grpcpp.h>
#include "common.grpc.pb.h"
#include "common.pb.h"
#include "adapter.h"
#include "Entities.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;

using player::Entity;
using player::Field;
using player::RpcService;

using std::string;
using std::vector;


class ServiceDemoImplement final : public RpcService::Service {
    Status RpcCall(ServerContext* context, const Entity* req, Entity* rsp ) override 
    {        
        auto request = unformalize(req); 
        print(request);
        Entities response;
        formalize(response, rsp);
        return Status::OK;
    }
    Command unformalize(const Entity* req)
    {
        Command cmd;
        Adapter::grpc2cpp(&cmd, req);
        return cmd;
    }
    void formalize(Entities &sums, Entity* rsp)
    {
        Adapter::cpp2grpc(&sums, rsp);
    }
    void print(Command& req)
    {
        std::cout<<"RPC Service Print"<<std::endl;
        std::cout<<req.command_type<<std::endl;
        std::cout<<req.speedup<<std::endl;
        std::cout<<req.step_time<<std::endl;
    }
};

void Run() {
    std::string address("0.0.0.0:50051");
    ServiceDemoImplement service;
    
    ServerBuilder builder;

    builder.AddListeningPort(address, grpc::InsecureServerCredentials());
    builder.RegisterService(&service);

    std::unique_ptr<Server> server(builder.BuildAndStart());
    std::cout << "Server listening on port: " << address << std::endl;

    server->Wait();
}

int main(int argc, char** argv) {
    Run();

    return 0;
}
